<template>
    <div class="app-container">
         <!-- 器材管理 -->
        <el-form size="small" :inline="true" :model="queryForm" ref="queryForm"  class="f1" border>
            <el-form-item label="器材名称" prop="ementName">
                <el-input v-model="queryForm.ementName" placeholder="请输入器材名称" @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item label="器材状态" prop="ementStatus" >
                    <el-select v-model="queryForm.ementStatus" placeholder="器材状态" clearable>
              <el-option label="正常" value="1"></el-option>
              <el-option label="故障" value="2"></el-option>
              <el-option label="维修" value="3"></el-option>
              <el-option label="报废" value="4"></el-option>
              </el-select>
          </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery()">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery()">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
              >新增</el-button>
            </el-col>
        </el-row>
        <!-- 器材信息 -->
        <el-table v-loading="loading" :data="tableData">
            <el-table-column type="index" label="编号" align="center"></el-table-column>
            <el-table-column prop="ementName" label="器材名称" key="ementName" align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="ementQuantity" label="器材数量" key="ementQuantity" align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column
              label="器材图片"
              align="center"
              key="ementPhoto"
              prop="ementPhoto"
              width="80"
            >
              <template slot-scope="scope">
                <el-carousel height="80px" width="80px" v-if="scope.row.ementPhoto">
                  <el-carousel-item
                    v-for="item in scope.row.ementPhoto.split(',')"
                    :key="item"
                  >
                    <ImagePreview :src="String(item)"></ImagePreview>
                  </el-carousel-item>
                </el-carousel>
                <el-tag v-else type="info">暂无数据</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ementStatus" label="器材状态" key="ementStatus" align="center" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_status" :value="scope.row.ementStatus"/>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="venueName" label="所属场馆" key="venueName" align="center" :show-overflow-tooltip="true" ></el-table-column> -->
            <el-table-column prop="display" label="是否展示" key="caseStatus" width="150" align="center">
                <template slot-scope="scope" >
                    <el-switch
                    v-model="scope.row.display"
                    active-value="1"
                    inactive-value="2"
                    active-text="显示"
                    inactive-text="不显示"
                    @change="handleStatus(scope.row)"
                  ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleRead(scope.row)"
                  >查看</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEdit(scope.row)"
                        >修改</el-button
                    >
                    <el-button style="color: red;" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryForm.pageNum"
        :limit.sync="queryForm.pageSize"
        @pagination="getList"
        />
        <!-- 添加或修改配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" @close="close" width="600px" append-to-body >
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="器材名称" prop="ementName">
                  <el-input v-model="form.ementName" placeholder="请输入器材名称" maxlength="30" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="器材品牌" prop="ementBrand">
                  <el-input v-model="form.ementBrand" placeholder="请输入器材品牌" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="器材型号" prop="ementModel">
                  <el-input v-model="form.ementModel" placeholder="请输入器材型号" maxlength="50" />
                  <span slot="label">
                    <el-tooltip content="器材型号只能包含字母、数字和字符-。例如（XX-0001A）" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    器材型号
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="器材图片">
                      <el-upload
                      class="avatar-uploader"
                      action=""
                      :multiple="true"
                      :on-remove="handleRemove"
                      :on-change="handlechange"
                      list-type="picture-card"
                      :before-upload="beforeAvatarUpload"
                      accept=".jpg,.jpeg,.png,.gif"
                      :auto-upload="false"
                      :file-list="fileList"
                      >
                      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="器材数量" prop="ementQuantity">
                  <el-input-number v-model="form.ementQuantity" placeholder="请输入器材数量" :min="1" :max="50"></el-input-number>
                  <span slot="label">
                    <el-tooltip content="器材数量最多不能超过50" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    器材数量
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                  <el-form-item label="器材长度" prop="ementLength">
                    <el-input v-model="form.ementLength" placeholder="长度(mm)" maxlength="4">
                      <template slot="append">mm</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="器材宽度" prop="ementWidth">
                    <el-input v-model="form.ementWidth" placeholder="宽度(mm)" maxlength="4">
                      <template slot="append">mm</template>
                    </el-input>
                  </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="器材高度" prop="ementHeight">
                  <el-input v-model="form.ementHeight" placeholder="高度(mm)"  maxlength="4">
                    <template slot="append">mm</template>
                </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="器材状态" prop="ementStatus">
                  <el-radio-group v-model="form.ementStatus">
                    <el-radio label="1">正常</el-radio>
                    <el-radio label="2">故障</el-radio>
                    <el-radio label="3">维修</el-radio>
                    <el-radio label="4">报废</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.ementStatus == '4'">
              <el-col :span="12">
                <el-form-item label="报废原因" prop="reason">
                  <el-input v-model="form.reason" placeholder="请输入报废原因"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="是否显示" prop="display">
                  <el-radio-group v-model="form.display">
                    <el-radio label="1">显示</el-radio>
                    <el-radio label="2">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
         <!-- 查看详情对话框 -->
        <el-dialog title="器材详情" :visible.sync="dialogTableVisible">
          <el-descriptions class="margin-top" :column="2" :size="size" border>
            <el-descriptions-item>
              <template slot="label">
                器材名称
              </template>
              {{ gridData.ementName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材数量
              </template>
              {{ gridData.ementQuantity }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材品牌
              </template>
              {{ gridData.ementBrand }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材型号
              </template>
              {{ gridData.ementModel }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材长度
              </template>
              {{ gridData.ementLength }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材宽度
              </template>
              {{ gridData.ementWidth }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-location-outline"></i>
                器材高度
              </template>
              {{ gridData.ementHeight }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                添加时间
              </template>
              {{ gridData.createTime }}
            </el-descriptions-item>
            <el-descriptions-item v-if="gridData.ementStatus =='4'">
              <template slot="label">
                报废时间
              </template>
              {{ gridData.scrapTime }}
            </el-descriptions-item>
            <el-descriptions-item v-if="gridData.ementStatus =='4'">
              <template slot="label">
                报废原因
              </template>
              {{ gridData.reason }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材状态
              </template>
              <dict-tag :options="dict.type.equipment_status" :value="gridData.ementStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                是否展示
              </template>
              <dict-tag :options="dict.type.equipment_display" :value="gridData.display"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                所属场馆
              </template>
              {{ gridData.venueName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                器材图片
              </template>
              <el-carousel  width="100px" v-if="gridData.ementPhoto">
                <el-carousel-item
                  v-for="item in gridData.ementPhoto.split(',')"
                  :key="item"
                >
                  <ImagePreview :src="String(item)"></ImagePreview>
                </el-carousel-item>
              </el-carousel>
              <el-tag v-else type="info">暂无数据</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-dialog>
    </div>
</template>
<script>
import { listEquipment,editEmentDisplay,editEquipement,addEquipement,removeEmentById,listvenueManagementByVenueId } from '@/api/equipement/ement/index'
export default {
    dicts: [ 'equipment_status','equipment_display' ],
    data(){
        const validateEquipmentModel = (rule, value, callback) => {
          const reg = /^[A-Za-z0-9-]+$/; // 只允许字母和数字
          if (!reg.test(value)) {
            callback(new Error('器材型号只能包含字母、数字和字符-'));
          } else {
            callback();
          }
        };
        const validateEmentQuantity = (rule, value, callback) => {
          if (!Number.isInteger(value) || value < 1 || value > 50) {
            callback(new Error('数量必须为整数且不能超过50'));
          } else {
            callback();
          }
        };
        return{
            //表格数据
            tableData: [],
            // 查询参数
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                ementStatus: '',
                ementName: '',
                venueUniqueIdentifier: window.sessionStorage.getItem('venueUniqueIdentifier'),
            },
            venueUniqueIdentifier: window.sessionStorage.getItem('venueUniqueIdentifier'),
            venueName:'',
            dialogTableVisible: false,
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            delImageIds: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 表单参数
            form: {
              delImageIds: undefined,
              stationId:0,
              venueUniqueIdentifier: ''
            },
            queryParams:{
              pageNum: 1,
              pageSize: 10,
              ementId: '',
            },
            //存储图片数组
            fileList: [],
            gridData: {},
            imageUrl: "",
            imageFile: File,
            imgUrl: process.env.VUE_APP_IMG_BASE_URL,
            size: '',
            rules:{
              ementName: [
                { required: true, message: '器材名称不能为空', trigger: 'blur' }
              ],
              ementBrand: [
                { required: true, message: '器材品牌不能为空', trigger: 'blur' }
              ],
              ementModel: [
                { required: true, message: '器材型号不能为空', trigger: 'blur' },
                { validator: validateEquipmentModel, trigger: 'blur' }
              ],
              ementQuantity: [
                { required: true, message: '器材数量不能为空', trigger: 'blur' },
                { validator: validateEmentQuantity, trigger: 'blur' }
              ],
              ementLength: [
                { required: true, message: '器材长度不能为空', trigger: 'blur' }
              ],
              ementWidth: [
                { required: true, message: '器材宽度不能为空', trigger: 'blur' }
              ],
              ementHeight: [
                { required: true, message: '器材高度不能为空', trigger: 'blur' }
              ],
              ementStatus: [
                { required: true, message: '请选择当前器材状态', trigger: 'blur' }
              ],
              display: [
                { required: true, message: '请选择是否显示', trigger: 'blur' }
              ]
            },
        }
    },
    created(){
        this.getList();
        this.listvenueManagementByVenueId();
    },
    methods: {
        //查询案例信息
        getList(){
            this.loading = true;
            listEquipment(this.addDateRange(this.queryForm)).then(res => {
                this.tableData = res.data.records;
                this.total = res.data.total;
                this.loading = false;
            })
        },
        listvenueManagementByVenueId(){
          listvenueManagementByVenueId({ venueUniqueIdentifier: this.venueUniqueIdentifier }).then(res => {
              var sId = res.data.map(item => item.id);
              this.form.stationId = sId
              // var vname = res.data.map(item => item.venueName);
              // this.venueName = vname.join(','); // 使用逗号分隔符将数组元素连接成字符串
            })
        },
        // 表单重置
        reset() {
          this.fileList=[];
          this.form = {};
          this.resetForm("form");
        },
        handleRead(row){
          this.dialogTableVisible = true;
          this.gridData = JSON.parse(JSON.stringify(row));
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryForm.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        handlechange(fileList) {
            this.fileList.push(fileList);
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.listvenueManagementByVenueId();
            this.form.venueUniqueIdentifier = window.sessionStorage.getItem('venueUniqueIdentifier'),
            this.title = "添加器材";
        },
        /** 器材显示操作 */
        handleStatus(row) {
            let text = row.display === '1' ? "显示" : "不显示";
            this.$modal.confirm('确认要将器材' + row.ementId + '进行'+text+'操作吗？').then(function() {
                return editEmentDisplay(row.ementId, row.display);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
                this.getList()
            }).catch(function() {
                row.display = row.display === '1' ? '2' : '1';
            });
        },
        // 提交
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                if (this.fileList.length > 5) {
                    this.$modal.msgError("上传图片不能超过5张");
                    return false;
                }
                var formdata = new FormData();
                formdata.set("ementId", this.form.ementId);
                formdata.set("ementName", this.form.ementName);
                formdata.set("ementBrand", this.form.ementBrand);
                formdata.set("ementModel", this.form.ementModel);
                formdata.set("ementQuantity", this.form.ementQuantity);
                formdata.set("ementLength", this.form.ementLength);
                formdata.set("ementWidth", this.form.ementWidth);
                formdata.set("ementHeight", this.form.ementHeight);
                formdata.set("ementStatus", this.form.ementStatus);
                formdata.set("display", this.form.display);
                formdata.set("stationId", this.form.stationId);
                if(this.form.reason != null && this.form.reason != undefined){
                  formdata.set("reason", this.form.reason);
                }
                formdata.set("venueUniqueIdentifier",this.form.venueUniqueIdentifier)
                if (this.fileList.length > 0) {
                    this.fileList.forEach((item) => {
                        formdata.append("files", item.raw);
                    });
                }
                if (this.form.ementId != '' && this.form.ementId != null && this.form.ementId != undefined) {
                    formdata.set("ementPhoto", this.form.ementPhoto);
                    formdata.set("delImageIds", this.delImageIds.join(','));
                    editEquipement(formdata)
                    .then((response) => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.fileList = [];
                        this.getList();
                    })
                    .catch((e) => {
                        this.$modal.msgError(e);
                    });
                } else {
                  if(this.form.ementId === '' || this.form.ementId === null || this.form.ementId === undefined) {
                    formdata.set('ementId',0)
                    addEquipement(formdata)
                      .then((response) => {
                          this.$modal.msgSuccess("新增成功");
                          this.open = false;
                          this.fileList = [];
                          this.getList();
                      })
                      .catch((e) => {
                          this.$modal.msgError(e);
                      });
                    }
                }
                }
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        close() {
            this.fileList = [];
            this.imageUrl = ""
            this.open = false;
        },
         /** 删除按钮操作 */
         handleDelete(row) {
            const ementId = row.ementId
            if(row.display === '2'){
                this.$modal.confirm('是否确认删除器材编号为"' + ementId + '"的数据项？').then(function() {
                    return removeEmentById(ementId);
                }).then(() => {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }).catch(() => {});
            }else{
                this.$modal.msgError("请先关闭此器材显示，在进行删除操作！");
            }

        },
       // 修改按钮操作
       handleEdit(row) {
        if(row.ementStatus == '4'){
          this.$modal.msgError("此器材已报废无法进行修改");
        }else{
          const that = this;
            this.reset();
            this.form = JSON.parse(JSON.stringify(row));
            const ementPhotos = row.ementPhoto;
            if (ementPhotos != 'null' && ementPhotos != undefined) {
              const ementPhotoIds = ementPhotos.split(',');
              if (ementPhotoIds.length > 0) {
                ementPhotoIds.forEach(id => {
                  if (id !== '') {
                    this.fileList.push({ url: that.imgUrl + id, id: id });
                  }
                });
              }
            }
            this.title = "修改器材信息";
            this.listvenueManagementByVenueId();
            this.$nextTick(() => {
              this.open = true; // 打开弹窗
            });
          }
        },
        // 图片上传之前的校验方法
        beforeAvatarUpload(file) {
            const isPNG = file.type === "image/png";
            const isJPG = file.type === "image/jpg";
            const isJPEG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPNG && !isJPEG) {
                this.$message.error("上传图片只能是 JPG,格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
            }
            return true;
        },
        handleRemove(file) {
            // 删除照片
            if (file.id) {
                const ementPhoto = this.form.ementPhoto;
                let arrImgIds = ementPhoto.split(",");
                arrImgIds = arrImgIds.filter((item) => {
                    return item !== file.id && item !== "";
                });
                this.delImageIds.push(file.id)
                const index = this.fileList.indexOf(file);
                if (index !== -1) {
                    this.fileList.splice(index, 1);
                }
                this.form.ementPhoto = arrImgIds.join(",");
            } else {
                this.fileList = this.fileList.filter((item) => {
                    return file.name !== item.name && file.url !== item.url;
                });
            }
        },
    }
}
</script>
